import networkx as nx
import networkx.classes.function as nxf

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

attr = "id;name;weight;type;other_info".split(";")

with open("newmovies.txt", "r", encoding='utf8') as f:
    lines = f.readlines()

# 处理数据
k = int(lines[0].split()[1])
Vertices_0 = [line.split("\t") for line in lines[1:k + 2]]
Vertices = [(v[0], {attr[i]:v[i] for i in range(1,5)}) for v in Vertices_0]

Edge = dict()
for line in lines[k + 3:]:
    z = line.split()
    tmp = Edge.get(z[0], dict())
    tmp[z[1]] = int(z[2])
    Edge[z[0]] = tmp

G = nx.Graph(Edge)
G.add_nodes_from(Vertices)
# print(G.number_of_nodes())
# print(G.number_of_edges())

# 计算平均度
ver_num = nxf.number_of_nodes(G)
deg = nxf.number_of_edges(G)*2
print(f"\n该图的平均度数为{deg/ver_num}")

# 计算属性分布


# 计算度分布
deg_hist_list = nxf.degree_histogram(G)


# 绘制节点属性分布结果


# 绘制度的分布图
x = np.arange(1, len(deg_hist_list)+1)
y = deg_hist_list
plt.title("Degree Hist") 
plt.xlabel("Degree") 
plt.ylabel("Freq") 
plt.plot(x,y) 
plt.show()